﻿using System;
using System.Threading;
using System.Windows;
using System.Windows.Threading;
using Nutshell.Log;

namespace Nutshell.DSS.WPFUI
{
        /// <summary>
        ///         App.xaml 的交互逻辑
        /// </summary>
        public partial class App : Application
        {
                public Mutex SingleMutex;

                public App()
                {
                        NLoger.Separate();

                        AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
                        DispatcherUnhandledException += Application_DispatcherUnhandledException;
                }

                private void Application_Startup(object sender, StartupEventArgs e)
                {
                        String appName = GetType().Namespace;
                        bool isNotEixst = true;
                        SingleMutex = new Mutex(true, appName, out isNotEixst);

                        if (!isNotEixst)
                        {
                                MessageBox.Show("程序已运行！");
                                Shutdown();
                                return;
                        }


                        var window = new MainWindow();
                        window.Closed += MainWindow_Closed;
                        window.Show();
                }

                private void MainWindow_Closed(object sender, EventArgs e)
                {
                        Current.Shutdown();
                }

                private void Application_DispatcherUnhandledException(object sender,
                        DispatcherUnhandledExceptionEventArgs e)
                {
                        NLoger.Fatal(e.Exception);
                        MessageBox.Show("当前应用程序发生了一个不曾预料的错误，操作无法继续，请联系软件发行方以协助改进这个问题，非常感谢！");

                        Current.Shutdown();
                }

                private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
                {
                        NLoger.Fatal((Exception) e.ExceptionObject);
                        MessageBox.Show("当前应用程序域发生了一个不曾预料的错误，操作无法继续，请联系软件发行方以协助改进这个问题，非常感谢！");

                        Current.Shutdown();
                }
        }
}